package com.pjhouse.core.common.persistence;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ibatis.SqlMapClientTemplate;

public class IBatisBaseRepository {

    /**
     * 注入 sqlMapClientTemplate
     */
    @Autowired
    private SqlMapClientTemplate sqlMapClientTemplate;

    protected void setSqlMapClientTemplate(SqlMapClientTemplate sqlMapClientTemplate) {
        this.sqlMapClientTemplate = sqlMapClientTemplate;
    }

    public Object queryForObject(String statementName, Object parameterObject) {
        return sqlMapClientTemplate.queryForObject(statementName, parameterObject);
    }

    public List<?> queryForList(String statementName, Object parameterObject) {
        return sqlMapClientTemplate.queryForList(statementName, parameterObject);
    }

    public Map<?, ?> queryForMap(String statementName, Object parameterObject, String keyProperty) {
        return sqlMapClientTemplate.queryForMap(statementName, parameterObject, keyProperty);
    }

    public Map<?, ?> queryForMap(String statementName, Object parameterObject, String keyProperty, String valueProp) {
        return sqlMapClientTemplate.queryForMap(statementName, parameterObject, keyProperty, valueProp);
    }

    public int update(String statementName, Object parameterObject) {
        return sqlMapClientTemplate.update(statementName, parameterObject);
    }

    public Object insert(String statementName, Object parameterObject) {
        return sqlMapClientTemplate.insert(statementName, parameterObject);
    }

    public Object insertOrUpdate(String countStatementName, String insertStatementName, String updateStatementName,
                                 Object parameterObject) {
        Integer count = (Integer) this.queryForObject(countStatementName, parameterObject);
        if (null != count && count.intValue() > 0) {
            return this.update(updateStatementName, parameterObject);
        }
        return this.insert(insertStatementName, parameterObject);
    }

    public List<?> queryForList(String statementName) {
        return sqlMapClientTemplate.queryForList(statementName);
    }

    public Object queryForObject(String statementName) {
        return sqlMapClientTemplate.queryForObject(statementName);
    }

    public int delete(String statementName) {
        return sqlMapClientTemplate.delete(statementName);
    }

    public int delete(String statementName, Object parameterObject) {
        return sqlMapClientTemplate.delete(statementName, parameterObject);
    }

    protected Logger getLogger() {
        return LoggerFactory.getLogger(this.getClass());
    }

}
